package store.lunangangster.engine.impl.helper;

import java.util.List;
import java.util.stream.Collectors;
import store.lunangangster.bpmn.model.Message;
import store.lunangangster.bpmn.model.definition.MessageEventDefinition;
import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.entity.MesListenerEntity;
import store.lunangangster.engine.impl.entity.mgr.ExecutionEntityManager;
import store.lunangangster.engine.impl.entity.mgr.MesListenerEntityManager;
import store.lunangangster.engine.repository.Execution;

public class MessageHelper {

  public static void sendMessage(MessageEventDefinition messageEventDefinition, Execution execution) {
    Message message = messageEventDefinition.getMessage();
    MesListenerEntityManager mesListenerManager = Context.getProcessEngineConfiguration()
        .getMesListenerEntityManager();
    ExecutionEntityManager executionManager = Context.getProcessEngineConfiguration()
        .getExecutionEntityManager();
    List<MesListenerEntity> mesListenerEntities = mesListenerManager.selectMesListenerByMessageId(message.getId());

    executionManager.selectExecutionList(
        mesListenerEntities.stream()
            .map(MesListenerEntity::getExecutionId)
            .collect(Collectors.toList())).forEach(exec -> {
              Context.getCommandContext().getAgenda().addTriggerExecutionOperation(exec);
    });
    // MesListener的删除并不在此处，而是在消息监听者被激活后才删除
  }

  public static void listenToMessage(MessageEventDefinition messageEventDefinition, Execution execution) {
    Message message = messageEventDefinition.getMessage();
    MesListenerEntityManager mesListenerManager = Context.getProcessEngineConfiguration()
        .getMesListenerEntityManager();

    MesListenerEntity mesListenerEntity = mesListenerManager.create();
    mesListenerEntity.setExecutionId(execution.getId());
    mesListenerEntity.setProcessInstanceId(execution.getProcessInstanceId());
    mesListenerEntity.setProcessDefinitionId(execution.getProcessDefinitionId());
    mesListenerEntity.setMessageId(message.getId());

    mesListenerManager.insert(mesListenerEntity);
  }
}
